from json import dumps

import sqlalchemy
from sqlalchemy import and_
from flask import Blueprint, request
from datetime import datetime

from flask_jwt_extended import jwt_required

from models import *

duty = Blueprint('duty', __name__)


@duty.route('/api/checkDevice', methods=['POST'])
@jwt_required(refresh=True)
def checkDevice():
    """
    json格式示例:
    {
        "松下4K 180":[2, 3],
        "Sony NX3": [1, 2]
    }
    :return:
    """
    lastWeek = request.args.get('lastWeek')
    thisWeek = request.args.get('thisWeek')
    place = request.args.get('place', default='')
    record = HandOver()

    record.thisWeek = thisWeek
    record.lastWeek = lastWeek
    record.time = datetime.now()

    jsonData = request.json
    DeviceStatus.query.filter(and_(DeviceStatus.state == '在库', DeviceStatus.place == place)).update(dict(state='遗失'))
    sqlStrHead = "update DeviceStatus set state='在库' where state='遗失' AND (FALSE "
    sqlStrCandition = "OR (name='%s' and ID in %s)"
    sqlStrTail = ")"
    sql = sqlStrHead
    for name in jsonData:
        if not jsonData[name]:
            continue
        this_device = jsonData[name]
        for i in this_device:
            if type(i) is not int:
                print(type(i))
                return "Forbidden", 403
        range_str = str(tuple(this_device)) if len(this_device) != 1 else "(%d)" % this_device[0]
        if ')' not in name:
            sql += sqlStrCandition % (name, range_str)
        else:
            return "Forbidden", 403
    sql += sqlStrTail
    db.session.execute(sql)
    record.havingDevice = dumps(jsonData, ensure_ascii=False)
    db.session.add(record)

    try:
        db.session.commit()
    except sqlalchemy.exc.IntegrityError:
        db.session.rollback()
        return '值日生信息有误', 403
    return '提交成功'
